<template>
  <view class="stages-fee-list">
    <div class="stages-fee-item" v-for="(item, index) in handledFeeDetailList" :key="index">
      <div class="stages-fee-item-title">{{ item.feeName }}</div>
      <div class="stages-fee-item-sub-list">
        <page-form-row>
          <stages-fee-item
            :feeList="item.childrenList"
            :feeIndex="feeChildIndex"
            v-for="(feeChildItem, feeChildIndex) in item.childrenList"
            :key="feeChildIndex"
          />
        </page-form-row>
      </div>
    </div>
  </view>
</template>
<script setup>
  import { inject, computed, watch } from 'vue'
  import stagesFeeItem from './stages-fee-item.vue'
  import { decimalAddition, decimalSubtract } from '@/utils'
  const props = defineProps({
    orderFeeIndex: Number,
    feeDetailList: {
      type: Array,
      default() {
        return []
      },
    },
  })
  const handledFeeDetailList = computed(() => {
    let detailList = props.feeDetailList
    let temp = [
      { feeCategory: 0, feeName: '基础费用', childrenList: [] },
      { feeCategory: 1, feeName: '增值服务费', childrenList: [] },
      { feeCategory: 2, feeName: '优惠费用', childrenList: [] },
      { feeCategory: 3, feeName: '其他费用', childrenList: [] },
    ]
    if (detailList && detailList.length > 0) {
      detailList.forEach((item) => {
        let feeCategory = item.feeCategory
        let targetIndex = temp.findIndex((tempItem) => tempItem.feeCategory == feeCategory)
        // 代表费用
        if (item.type == 1) {
          temp[targetIndex].childrenList.push(item)
        } else {
          // 代表目录
          temp[targetIndex].childrenList = item.childrenList
        }
      })
    }
    return temp.filter((item) => item.childrenList.length > 0)
  })

  const feeSum = computed(() => {
    let sum = 0
    if (props.feeDetailList) {
      props.feeDetailList.forEach((feeItem) => {
        if (feeItem.type == 1) {
          sum = decimalAddition(sum, feeItem.amount)
        } else {
          let feeChildrenList = feeItem.childrenList
          if (feeChildrenList?.length > 0) {
            feeChildrenList?.forEach((feeChildItem) => {
              if (feeChildItem.costType == 20) {
                sum = decimalSubtract(sum, feeChildItem.amount)
              } else {
                sum = decimalAddition(sum, feeChildItem.amount)
              }
            })
          }
        }
      })
    }
    return sum
  })
  const feeForm = inject('feeForm')
  watch(
    () => feeSum.value,
    (newVal) => {
      if (feeForm.value.orderFee[props.orderFeeIndex]) {
        feeForm.value.orderFee[props.orderFeeIndex].activeTotalAmount = newVal
      }
    }
  )
</script>
<style lang="less" scoped>
  .stages-fee-item {
    margin: 16px 0 0;
  }
  .stages-fee-item-title {
    font-size: 14px;
    font-weight: 600;
    color: #1d2129;
    line-height: 22px;
    margin-bottom: 4px;
  }
</style>
